const dayjs = require('dayjs');

/**
 * 查询报名数据
*/
const Service = require('egg').Service;

class UserService extends Service {
  constructor() {
    super(...arguments);
    /**
     *@abstract 初始化连接的数据库 db1
    */
    this.client1 = this.app.mysql.get('db1');
  }

  /**
   * 验证登录信息
  * @param username
  * @param password
  */
  async validateLogin(username, password) {
    const { ctx } = this;
    const { findOneDb, md5, updateDb } = ctx.helper;
    try {
      const user = await findOneDb(this.client1, 'tx_admin', { username });
      let body = {};
      // 更新用户最后登录时间
      const updatetime = Math.floor(new Date().getTime() / 1000);
      // 失败重试变量
      const numTimer = 5;
      const diffTimer = dayjs(updatetime * 1000).diff(user.updatetime * 1000, 'm');
      let loginfailure = user.loginfailure;
      // 说明账户名称正确, 需要验证密码
      if (user) {
        // 登录失败错误数达到3次之后,提示五分钟后再试
        if (user.loginfailure >= 3) {
          if (diffTimer < numTimer) {
            body = {
              code: 500,
              message: `登录失败次数超过限制, 请在${numTimer - diffTimer}分钟之后重试`,
            };
            return body;
          }
          loginfailure = 0;
          await updateDb(this.client1, 'tx_admin', {
            id: user.id,
            loginfailure,
          });
        }
        const pwd = md5([ md5(password), user.salt ].join(''));
        if (pwd === user.password) {
          const token = ctx.helper.createJwtToken(user.id);
          body = {
            code: 200,
            message: 'success',
            data: {
              token,
              user: {
                email: user.email,
                nickname: user.nickname,
                username: user.username,
              },
            },
          };
          // 更新最后登录时间
          await updateDb(this.client1, 'tx_admin', {
            id: user.id,
            logintime: updatetime,
            updatetime,
            loginfailure: 0,
          });
        } else {
          body = {
            code: 500,
            message: '密码错误',
          };
          // 更新登录失败次数
          await updateDb(this.client1, 'tx_admin', {
            id: user.id,
            loginfailure: loginfailure + 1,
            updatetime,
          });
        }
      } else {
        body = {
          code: 500,
          message: '请输入正确的账户密码',
        };
      }
      return body;
    } catch (error) {
      throw new Error(`登录失败${error}`);
    }
  }
}


module.exports = UserService;
